﻿using Microsoft.AspNetCore.Authorization;

namespace Devonline.Identity;

/// <summary>
/// 默认的基于策略的授权控制机制
/// </summary>
public class AuthorizationRequirement(AuthorizationService authorizationService) : AuthorizationHandler<AuthorizationRequirement>, IAuthorizationHandler, IAuthorizationRequirement
{
    protected readonly AuthorizationService _authorizationService = authorizationService;

    public override async Task HandleAsync(AuthorizationHandlerContext context)
    {
        await base.HandleAsync(context);
        if (context.HasSucceeded && (context.User.Identity?.IsAuthenticated ?? false))
        {
            //await _authorizationService.AuthorizeAsync();
            context.Succeed(this);
        }
        else
        {
            context.Fail(new AuthorizationFailureReason(this, "Resource Forbidion"));
        }
    }

    /// <summary>
    /// 此处仅针对已获取授权的
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    /// <returns></returns>
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationRequirement requirement)
    {
        if ((context.User.Identity?.IsAuthenticated ?? false))
        {
            //await _authorizationService.AuthorizeAsync()
            context.Succeed(requirement);
        }
        else
        {
            context.Fail(new AuthorizationFailureReason(this, "Resource Forbidion"));
        }

        await Task.CompletedTask;
    }
}